<script lang="ts" setup>
import {ElMessage, ElMessageBox} from 'element-plus'
import {reactive, ref} from 'vue'
import {formRules} from '@/rules/editCourseRule'
import CrudApi from '@/apis'
import HdTable from '@/components/hdTable.vue'
import {ResponseResult} from '#/result'
import {useRoute} from 'vue-router'

const {resource} = defineProps({
  resource: {type: String},
})

type CrudInterface = any
// 通用接口
const crudApi = new CrudApi<CrudInterface>(resource!)
// 列表数据
const crudList = ref<CrudInterface[]>([])
// 配置数据
const crudOptions = ref<crudTable.OptionsType>()
// 分页配置
const crudPageOption = reactive<crudTable.PageOption>({
  currentPage: 1,
  pageSize: 5,
  pageSizes: [5, 10, 20, 50, 100],
  total: 0,
  isSmall: false,
  isHasBackground: true,
  sort: {prop: 'name'},
  search: {value: '', prop: ''},
})
// 切换页数量
const handleSizeChange = (currentSize: number) => {
  crudPageOption.pageSize = currentSize
  fetch()
}
// 切换当前页
const handleCurrentChange = (currentPage: number) => {
  crudPageOption.currentPage = currentPage
  fetch()
}
// 排序
const handleSortChange = (sort: crudTable.SortInstance) => {
  if (sort.order === 'ascending') {
    crudPageOption.sort!.order = 1
  } else if (sort.order === 'descending') {
    crudPageOption.sort!.order = -1
  } else {
    crudPageOption.sort!.order = 0
  }
  fetch()
}
// 获取列表
const fetch = async () => {
  const route = useRoute()
  if (route?.path === '/content/episodes/list') {
    crudPageOption.populate = 'course'
  } else if (route?.path === '/content/categories/list') {
    crudPageOption.populate = 'parent'
  }
  const result = await crudApi.getResourceApi(crudPageOption)
  crudList.value = result.data?.data!
  crudPageOption.total = result.data?.total!
}
fetch()
// 获取表格配置
const fetchOptions = async () => {
  const result = await crudApi.getOptions()
  const searchProp = result.data?.columns.find(prop => prop.search)
  crudOptions.value = result.data
  crudPageOption.search!.prop = searchProp?.prop || '_id'
}
fetchOptions()
// 编辑
const editor = async (id: string, callback: Function) => {
  const result = await crudApi.getResourceApiById(id)
  callback(result.data)
}
// 提交
const editorSubmit = async (form: any) => {
  let result: ResponseResult<CrudInterface>
  if (form._id) {
    result = await crudApi.updateResourceApiById(form._id, form)
  } else {
    result = await crudApi.createResourceApi(form)
  }
  await fetch()
  if (result.code === 0) {
    ElMessage({
      message: form._id ? '修改成功' : '创建成功',
      type: 'success',
      showClose: true,
    })
  }
}
// 删除
const remove = (id: string) => {
  ElMessageBox.confirm('确定删除该课程吗', 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        const result = await crudApi.removeResourceApi(id)
        if (result.code === 0) {
          ElMessage({
            message: '删除成功',
            type: 'success',
            showClose: true,
          })
          await fetch()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
          showClose: true,
        })
      })
}
// 模糊搜索
const handleSearchChange = (value: string) => {
  crudPageOption.search!.value = value
  fetch()
}
</script>

<template>
  <div class="course">
    <hd-table
        v-if="crudOptions"
        :data="crudList"
        :options="crudOptions"
        :page-option="crudPageOption"
        :rules="formRules"
        @CurrentChange="handleCurrentChange"
        @Editor="editor"
        @Remove="remove"
        @SearchChange="handleSearchChange"
        @SizeChange="handleSizeChange"
        @SortChange="handleSortChange"
        @Submit="editorSubmit"
    ></hd-table>
  </div>
</template>

<style lang="scss" scoped>
.course {
  .search {
    display: flex;
    width: 400px;
    padding: 10px 0;

    .el-input {
      margin-right: 15px !important;
    }
  }
}
</style>
